﻿Public Delegate Sub CheckBoxClickedHandler(ByVal state As Boolean)
Public Class DataGridViewCheckBoxHeaderCellEventArgs
    Inherits EventArgs
    Private _bChecked As Boolean
    Public Sub New(ByVal bChecked As Boolean)
        _bChecked = bChecked
    End Sub
    Public ReadOnly Property Checked() As Boolean
        Get
            Return _bChecked
        End Get
    End Property
End Class
Class DatagridViewCheckBoxHeaderCell
    Inherits DataGridViewColumnHeaderCell
    Private checkBoxLocation As Point
    Private checkBoxSize As Size
    Private _checked As Boolean = False
    Private _cellLocation As New Point()
    Private _cbState As System.Windows.Forms.VisualStyles.CheckBoxState = System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal
    Public Event OnCheckBoxClicked As CheckBoxClickedHandler

    Public Sub New()
    End Sub

    Protected Overloads Overrides Sub Paint(ByVal graphics As System.Drawing.Graphics, ByVal clipBounds As System.Drawing.Rectangle, ByVal cellBounds As System.Drawing.Rectangle, ByVal rowIndex As Integer, ByVal dataGridViewElementState As DataGridViewElementStates, ByVal value As Object, _
     ByVal formattedValue As Object, ByVal errorText As String, ByVal cellStyle As DataGridViewCellStyle, ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, ByVal paintParts As DataGridViewPaintParts)
        MyBase.Paint(graphics, clipBounds, cellBounds, rowIndex, dataGridViewElementState, value, _
         "", errorText, cellStyle, advancedBorderStyle, paintParts)
        Dim p As New Point()
        Dim s As Size = CheckBoxRenderer.GetGlyphSize(graphics, System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal)
        p.X = CInt(cellBounds.Location.X + (cellBounds.Width / 2) - (s.Width / 2))
        p.Y = CInt(cellBounds.Location.Y + (cellBounds.Height / 2) - (s.Height / 2))
        _cellLocation = cellBounds.Location
        checkBoxLocation = p
        checkBoxSize = s
        If _checked Then
            _cbState = System.Windows.Forms.VisualStyles.CheckBoxState.CheckedNormal
        Else
            _cbState = System.Windows.Forms.VisualStyles.CheckBoxState.UncheckedNormal
        End If
        CheckBoxRenderer.DrawCheckBox(graphics, checkBoxLocation, _cbState)
    End Sub

    Protected Overloads Overrides Sub OnMouseClick(ByVal e As DataGridViewCellMouseEventArgs)
        Dim p As New Point(e.X + _cellLocation.X, e.Y + _cellLocation.Y)
        If p.X >= checkBoxLocation.X AndAlso p.X <= checkBoxLocation.X + checkBoxSize.Width AndAlso p.Y >= checkBoxLocation.Y AndAlso p.Y <= checkBoxLocation.Y + checkBoxSize.Height Then
            _checked = Not _checked
            RaiseEvent OnCheckBoxClicked(_checked)
            Me.DataGridView.InvalidateCell(Me)
        End If
        MyBase.OnMouseClick(e)
    End Sub
End Class
